//
//  HJMenuView.m
//  MenuView
//
//  Created by uniqhj on 2018/8/31.
//

#import "HJMenuView.h"
#import "HJUpDownBtn.h"

#define kMenueWidth 60
#define kMenueMargin 20

@implementation HJMenuView

-(void)layoutSubviews {
    [super layoutSubviews];
    
    NSInteger count = self.menuModels.count;
    CGFloat h = self.frame.size.height;
    for(int i = 0; i < count; i++)
    {
        UIView *subView = self.subviews[i];
        subView.frame = CGRectMake(i * (kMenueWidth + kMenueMargin) + kMenueMargin, 0, kMenueWidth, h);
    }
    
    self.contentSize = CGSizeMake((kMenueWidth + kMenueMargin) * count + kMenueMargin, 0);
}

- (void)setMenuModels:(NSArray<id<MenuModelProtocol>> *)menuModels {
    _menuModels = menuModels;
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    NSInteger count = menuModels.count;
    for (int i = 0; i < count ; i ++) {
        id<MenuModelProtocol> model = menuModels[i];
        HJUpDownBtn *btn = [[HJUpDownBtn alloc] init];
        if (self.loadBlock) {
            self.loadBlock(btn, [NSURL URLWithString:model.imageURL]);
        }
        [btn setTitle:model.title forState:UIControlStateNormal];
        btn.tag = self.subviews.count;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
    }
    [self setNeedsLayout];
}

- (void)btnClick: (HJUpDownBtn *)upDownBtn {
    
    NSInteger tag = upDownBtn.tag;
    id<MenuModelProtocol> menueModel = self.menuModels[tag];
    if(menueModel.clickBlock != nil)
    {
        menueModel.clickBlock();
    }
    
}




@end
